﻿/*
 * 作者：刘李
 * 功能描述：套管具组合
 * 时间：2018-01-20
 * 修改人：
 * 修改时间：
 * 修改描述：完成增删查改
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DataAccess;
using DataBusiness;
using Entity;
using UI.BasicData;
using System.Data.OleDb;
using Common;

namespace UI
{
    public partial class frmDrillingComb : DevExpress.XtraEditors.XtraForm
    {
        private string well_ID = "";
        private string CombID = "CombID";
        private string WellNo = "WellNo";
        private string newRow_ID = "";
        private int isAddRow_index = -1;
        private int isAddRow_index2 = -1;
        private int menuInControl = -1;
        private DataTable initDt;
        private DataTable dtTools;

        private static List<DataTable> comb_tables = new List<DataTable>();
        private static BindingSource bindingSource1 = new BindingSource();
        private static List<BindingSource> bingings = new List<BindingSource>();
        private static List<string> tool_titles = new List<string>();
        private static List<string> comb_titles = new List<string>();
        private static List<string> comb_ID = new List<string>();

        RepositoryItemComboBox ricb_Comb = null;

        private DataRow dr_copy = null;

        public List<BindingSource> Binding_comb
        {
            get
            {
                return bingings;
            }
        }

        public BindingSource Binding_order
        {
            get
            {
                return bindingSource1;
            }
        }

        public List<string> Tool_titles
        {
            get
            {
                return tool_titles;
            }
        }

        public List<string> Comb_titles
        {
            get
            {
                return comb_titles;
            }
        }

        public List<string> Drilling_comb_ID
        {
            get
            {
                return comb_ID;
            }
        }

        public string Well_ID
        {
            get
            {
                return well_ID;
            }
        }


        public frmDrillingComb()
        {
            InitializeComponent();

            initDrillingTools();

            initDrillingCombs();
        }

        public frmDrillingComb(string well_id)
        {
            this.well_ID = well_id;

            InitializeComponent();

            initDrillingTools();

            initDrillingCombs();
        }

        /// <summary>
        /// 初始化左边gridcontrol
        /// </summary>
        private void initDrillingTools()
        {
            //initDt = AccessHelper.commSearch("well_drilling_tool");

            initDt = DrillCombBLL.GetDrillComb(well_ID).Tables[0];

            //获得原始表的标题
            for (int i = 0; i < initDt.Columns.Count; i++)
            {
                tool_titles.Add(initDt.Columns[i].Caption);
            }

            dtTools = new DataTable();
            dtTools.Columns.Add(new DataColumn(WellNo, typeof(string)));
            dtTools.Columns.Add(new DataColumn("开钻次序", typeof(string)));
            dtTools.Columns.Add(new DataColumn("井眼尺寸(mm)", typeof(decimal)));
            dtTools.Columns.Add(new DataColumn("井段-起(m)", typeof(decimal)));
            dtTools.Columns.Add(new DataColumn("井段-止(m)", typeof(decimal)));
            dtTools.Columns.Add(new DataColumn(CombID, typeof(string)));
            dtTools.Columns.Add(new DataColumn("UserID", typeof(Guid)));
            dtTools.Columns.Add(new DataColumn("InputDate", typeof(DateTime)));

            DataRow dr = null;


            foreach (DataRow row in initDt.Rows)
            {
                dr = dtTools.NewRow();
                dr[WellNo] = row[0];
                dr["开钻次序"] = row[1];
                dr["井眼尺寸(mm)"] = row[2];
                dr["井段-起(m)"] = row[3];
                dr["井段-止(m)"] = row[4];
                dr[CombID] = row[CombID];
                dr["UserID"] = row[6];
                dr["InputDate"] = row[7];
                dtTools.Rows.Add(dr);

                //以免用户删除完一个次序的所有工具后，在数据库中不能删除完全
                comb_ID.Add(row[CombID].ToString());
            }

            bindingSource1.DataSource = dtTools;
            gridControl1.DataSource = bindingSource1;

            gridView1.FocusedRowHandle = 0;
            //gridView1.Columns[WellNo].Visible = false;
            //gridView1.Columns[CombID].Visible = false;
            //gridView1.Columns["UserID"].Visible = false;
            //gridView1.Columns["InputDate"].Visible = false;

            gridView1.Columns[WellNo].OptionsColumn.AllowEdit = false;
            gridView1.Columns[CombID].OptionsColumn.AllowEdit = false;
            gridView1.Columns["UserID"].OptionsColumn.AllowEdit = false;
            gridView1.Columns["InputDate"].OptionsColumn.AllowEdit = false;

            gridControl1.Refresh();

            //创建钻具组合的table和binding
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                initTableHelper();
            }
        }


        /// <summary>
        /// 初始化右边gridcontrol
        /// </summary>
        private void initDrillingCombs()
        {
            //initDt = AccessHelper.commSearch("drilling_tool_comb");

            initDt = DrillCombBLL.GetDrillType().Tables[0];

            //获得原始表的标题
            for (int i = 0; i < initDt.Columns.Count; i++)
            {
                comb_titles.Add(initDt.Columns[i].Caption);
            }

            DataRow dr = null;
            DataTable dt = new DataTable();

            int count = 0;
            foreach (string id in comb_ID)
            {
                foreach (DataRow row in initDt.Rows)
                {
                    if (row["CombID"].ToString() == id)
                    {
                        dr = comb_tables[count].NewRow();

                        dr[CombID] = row[0];
                        dr["开钻工具"] = row[1];
                        dr["外径(mm)"] = row[2];
                        dr["长度"] = row[3];
                        comb_tables[count].Rows.Add(dr);
                    }
                }
                bingings[count].DataSource = comb_tables[count];
                count++;
            }

            //新建行绑定空表
            bingings[bingings.Count - 1].DataSource = comb_tables[bingings.Count - 1];

            ricb_Comb = new RepositoryItemComboBox();
            ricb_Comb.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            ricb_Comb.Items.Add("钻头");
            ricb_Comb.Items.Add("螺杆钻具");
            ricb_Comb.Items.Add("稳定器");
            ricb_Comb.Items.Add("浮阀");
            ricb_Comb.Items.Add("减震器");
            ricb_Comb.Items.Add("钻铤");
            ricb_Comb.Items.Add("钻杆");
            ricb_Comb.Items.Add("无磁钻铤");
            ricb_Comb.Items.Add("赔长短节");
            ricb_Comb.Items.Add("随钻震击器");
            ricb_Comb.Items.Add("方保");
            ricb_Comb.Items.Add("六方钻杆");
            ricb_Comb.Items.Add("添加自定义");

            //加载数据
            gridControl2.DataSource = bingings[0];
            gridView2.Columns["开钻工具"].ColumnEdit = ricb_Comb;
            //   gridView2.Columns["ID"].Visible = false;
            gridView2.Columns[CombID].Visible = false;
            gridView2.Columns[CombID].OptionsColumn.AllowEdit = false;
            gridView2.FocusedRowHandle = -1;
            gridControl2.Refresh();
        }

        /// <summary>
        /// 初始化数据加载
        /// </summary>
        private void initTableHelper()
        {
            DataTable dt = new DataTable();
            //       dt.Columns.Add(new DataColumn("ID", typeof(string)));
            dt.Columns.Add(new DataColumn(CombID, typeof(string)));
            dt.Columns.Add(new DataColumn("开钻工具", typeof(string)));
            dt.Columns.Add(new DataColumn("外径(mm)", typeof(decimal)));
            dt.Columns.Add(new DataColumn("长度", typeof(decimal)));
            comb_tables.Add(dt);

            BindingSource bs = new BindingSource();
            bs.BindingComplete += new BindingCompleteEventHandler(bindingSource_mBindingComplete);
            bingings.Add(bs);
        }

        /// <summary>
        /// 焦点行获取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            //    MessageBox.Show(e.FocusedRowHandle.ToString());

            object temp = gridView1.GetRowCellValue(e.FocusedRowHandle, "开钻次序");
            string drillOrder = (temp != null) ? temp.ToString() : "null";
            groupControl2.Text = " " + drillOrder + " 的钻具组合";

            if (bingings.Count != 0)
            {
                //选中新建行
                if (gridView1.FocusedRowHandle < 0)
                {
                    gridControl2.DataSource = bingings[bingings.Count - 1];
                }
                else
                {
                    gridControl2.DataSource = bingings[gridView1.FocusedRowHandle];
                }

                //     gridView2.Columns[0].ColumnEdit = ricb_Comb;
                gridView2.FocusedRowHandle = -1;
                gridControl2.Refresh();
            }

            //新行初始化完
            if (isAddRow_index >= 0)
            {
                newRow_ID = Guid.NewGuid().ToString("N");

                gridView1.SetRowCellValue(isAddRow_index - 1, gridView1.Columns[0], well_ID);
                gridView1.SetRowCellValue(isAddRow_index - 1, CombID, newRow_ID);
                gridView1.SetRowCellValue(isAddRow_index - 1, "UserID", "38b878f6-70e7-4fae-ad58-7aef5abf14bb");
                gridView1.SetRowCellValue(isAddRow_index - 1, "InputDate", DateTime.Now);

                comb_ID.Add(newRow_ID);
                isAddRow_index = -1;
            }
        }

        private void gridView2_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            //新行初始化完
            if (isAddRow_index2 >= 0)
            {
                //    MessageBox.Show(gridView1.FocusedRowHandle.ToString());
                gridView2.SetRowCellValue(isAddRow_index2 - 1, CombID, gridView1.GetRowCellValue(gridView1.FocusedRowHandle, CombID));
                isAddRow_index2 = -1;
            }
        }


        /// <summary>
        /// 显示行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle >= 0)
                {
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                }
                else if (e.RowHandle < 0 && e.RowHandle > -1000)
                {
                    e.Info.Appearance.BackColor = System.Drawing.Color.AntiqueWhite;
                    e.Info.DisplayText = "G" + e.RowHandle.ToString();
                }
            }
        }

        private void gridView2_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle >= 0)
                {
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                }
                else if (e.RowHandle < 0 && e.RowHandle > -1000)
                {
                    e.Info.Appearance.BackColor = System.Drawing.Color.AntiqueWhite;
                    e.Info.DisplayText = "G" + e.RowHandle.ToString();
                }
            }
        }

        /// <summary>
        /// 添加新行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            initTableHelper();
            bingings[bingings.Count - 1].DataSource = comb_tables[bingings.Count - 1];

            //     MessageBox.Show("添加了一行"+e.RowHandle+" "+ gridView1.RowCount);
        }

        private void gridView2_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {

        }


        /// <summary>
        /// 同步更新？？？？？？？？？？
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bindingSource1_BindingComplete(object sender, BindingCompleteEventArgs e)
        {
            // Check if the data source has been updated, and that no error has occured.
            if (e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate && e.Exception == null)
            {
                // If not, end the current edit.
                e.Binding.BindingManagerBase.EndCurrentEdit();
                gridControl1.DataSource = bindingSource1;
                gridControl1.Refresh();
            }
            //     MessageBox.Show("触发了");
        }

        //自定义BindingComplete函数
        private void bindingSource_mBindingComplete(object sender, BindingCompleteEventArgs e)
        {
            // Check if the data source has been updated, and that no error has occured.
            if (e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate && e.Exception == null)
            {
                // If not, end the current edit.
                e.Binding.BindingManagerBase.EndCurrentEdit();
                gridControl2.DataSource = bindingSource1;
                gridControl2.Refresh();
            }
        }

        public static DataTable getCombsTable()
        {
            /*
            DataTable dt = (bingings[0].DataSource as DataTable).Clone();
            foreach (BindingSource b in bingings)
            {
                foreach (DataRow d in (b.DataSource as DataTable).Rows)
                {
                    dt.ImportRow(d);
                }
            }
            */
            DataTable dt = comb_tables[0].Clone();
            foreach (DataTable d in comb_tables)
            {
                foreach (DataRow dr in d.Rows)
                {
                    dt.ImportRow(dr);
                }
            }
            return dt;
        }

        /// <summary>
        /// 保存到数据库(增删改)
        /// </summary>
        public static void saveToDataBase()
        {
            int flag1 = 0;
            int flag2 = 0;

            int rows = (bindingSource1.DataSource as DataTable).Rows.Count + (getCombsTable() as DataTable).Rows.Count;

            tb_DrillModel.TypeModel tt = new tb_DrillModel.TypeModel();

            tb_DrillModel.CombModel tc = new tb_DrillModel.CombModel();

            foreach (string id in comb_ID)
            {
                DrillCombBLL.DeleteDrillComb(id);
                DrillCombBLL.DeleteDrillType(id);
            }

            foreach (DataRow row in (bindingSource1.DataSource as DataTable).Rows)
            {

                tt.WellNo = row[0].ToString();
                tt.DrillingSequence = row[1].ToString();
                tt.HoleSize = (decimal)row[2];
                tt.HoleSection_start = (decimal)row[3];
                tt.HoleSection_end = (decimal)row[4];
                tt.CombID = row[5].ToString();
                tt.UserID = (Guid)row[6];
                tt.InputDate = (DateTime)row[7];

                flag1 += DrillCombBLL.InsertDrillType(tt, tool_titles);
            }

            foreach (DataRow row in (getCombsTable() as DataTable).Rows)
            {
                tc.CombID = row[0].ToString();
                tc.Name = row[1].ToString();
                tc.OutsideDiameter = (decimal)row[2];
                tc.ToolsLength = (decimal)row[3];

                flag2 += DrillCombBLL.InsertDrillComb(tc, comb_titles);
            }

            if (flag1 + flag2 == rows)
            {
                XtraMessageBox.Show("数据已成功保存！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                XtraMessageBox.Show("数据保存失败！", "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //获取是否为新建行
        private void gridView1_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            //  MessageBox.Show(e.Column + ", " + e.RowHandle);          
            if (e.RowHandle < 0)
            {
                isAddRow_index = gridView1.RowCount;
            }
        }

        private void gridView2_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            //    MessageBox.Show(e.Column + ", " + e.RowHandle); 
            if (e.RowHandle < 0)
            {
                isAddRow_index2 = gridView2.RowCount;
            }
        }

        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Text)
            {
                case "复制":
                    menuInControl_Event(menuInControl);

                    dr_copy = (bindingSource1.DataSource as DataTable).Rows[gridView1.FocusedRowHandle];







                    //赋值gridView1行时需重新加载uuid
                    //   MessageBox.Show(dr_copy[5]+"");
                    dr_copy[CombID] = Guid.NewGuid().ToString("N");








                    break;
                case "删除":
                    if (menuInControl == 1 && XtraMessageBox.Show("你确定要删除该行并且相应 钻具组合 也一起删除吗？", "提示",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                    {
                        //删除其相应组合
                        comb_tables[gridView1.FocusedRowHandle].Clear();
                        gridView1.DeleteSelectedRows();
                    }
                    if (menuInControl == 2 && XtraMessageBox.Show("你确定要删除该行吗？", "提示",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                    {
                        gridView2.DeleteSelectedRows();
                    }
                    break;
                case "粘贴":
                    if (dr_copy != null)
                    {





                    }

                    break;
                case "刷新":
                    this.Invalidate();
                    gridControl1.Refresh();
                    gridView1.FocusedRowHandle = -1;
                    gridControl2.Refresh();
                    gridView2.FocusedRowHandle = -1;
                    break;
            }
        }

        private void menuInControl_Event(int menuInControl)
        {

        }


        private void contextMenuStrip1_Opened(object sender, EventArgs e)
        {
            string controlName = (sender as ContextMenuStrip).SourceControl.Name;
            //MessageBox.Show(controlName);

            switch (controlName)
            {
                case "gridControl1":
                    menuInControl = 1;
                    foreach (ToolStripItem tsi in contextMenuStrip1.Items)
                    {
                        tsi.Enabled = true;
                    }
                    break;
                case "gridControl2":
                    menuInControl = 2;
                    foreach (ToolStripItem tsi in contextMenuStrip1.Items)
                    {
                        tsi.Enabled = true;
                    }
                    break;
                case "frmDrillingComb":
                    menuInControl = 0;
                    //contextMenuStrip1.Items[0].Enabled = false;
                    contextMenuStrip1.Items[1].Enabled = false;
                    contextMenuStrip1.Items[2].Enabled = false;
                    contextMenuStrip1.Items[3].Enabled = false;
                    contextMenuStrip1.Items[4].Enabled = false;
                    contextMenuStrip1.Items[5].Enabled = false;
                    break;
            }
        }

        private void sBtn_import_Click(object sender, EventArgs e)
        {
            AppMethod.ImportFile(gridControl1);
        }

        private void sBtn_export_Click(object sender, EventArgs e)
        {
            AppMethod.ExportFile(gridView1);
        }

    }
}